package cn.hs.service.impl;

import cn.hs.entity.CourseTalk;
import cn.hs.mapper.CourseReplyMapper;
import cn.hs.mapper.CourseTalkMapper;
import cn.hs.mapper.UserMapper;
import cn.hs.service.CourseTalkService;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;

/**
 * @ClassName CourseTalkServiceImpl
 * @Description TODO
 * @Author wsh
 * @Date 2024年10月28日 11:38
 * @Version 1.0
 */
@Service
public class CourseTalkServiceImpl implements CourseTalkService {
    @Autowired
    private CourseTalkMapper courseTalkMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private CourseReplyMapper replyMapper;
    @Override
    public List<CourseTalk> find(CourseTalk courseTalk) {

        List<CourseTalk> list = courseTalkMapper.find(courseTalk);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setUserName(userMapper.selectById(list.get(i).getUserId()).getUsername());
            list.get(i).setReplyCount(replyMapper.selectCountByTalkId(list.get(i).getId(),list.get(i).getUserId()));
        }
        return list;
    }

    @Override
    public List<CourseTalk> find1(CourseTalk courseTalk) {
        List<CourseTalk> list = courseTalkMapper.find1(courseTalk);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setUserName(userMapper.selectById(list.get(i).getUserId()).getUsername());
            list.get(i).setReplyCount(replyMapper.selectCountByTalkId(list.get(i).getId(),list.get(i).getUserId()));
        }
        return list;
    }

    @Override
    public List<CourseTalk> findAllOrderByCount(CourseTalk courseTalk) {
        List<CourseTalk> list = courseTalkMapper.find(courseTalk);
        for (int i = 0; i < list.size(); i++) {
            list.get(i).setUserName(userMapper.selectById(list.get(i).getUserId()).getUsername());
            list.get(i).setReplyCount(replyMapper.selectCountByTalkId(list.get(i).getId(),list.get(i).getUserId()));
        }
        list.sort(Comparator.comparing(CourseTalk::getReplyCount).reversed());
        return list;
    }

    @Override
    public int insert(CourseTalk courseTalk) {
        return courseTalkMapper.insertAll(courseTalk);
    }
}
